package jwlee.testlog;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;

import org.apache.log4j.jdbc.JDBCAppender;
import org.apache.log4j.spi.LoggingEvent;

public class MyJDBCAppender extends JDBCAppender {
	private LoggingEvent e;

	protected void execute(String sql) throws SQLException {
		//System.out.println("sql : " + this.getSql());
		//INSERT INTO LOG4J (LOGTIMESTAMP,LOGGERNAME,LOGLEVEL,LOCATION,MESSAGE) VALUES (?,?,?,?,?)
		Connection con = null;
		PreparedStatement stmt = null;
		try {
			con = getConnection();
			stmt = con.prepareStatement(this.getSql());
			stmt.setTimestamp(1, new Timestamp(e.getTimeStamp()));
			stmt.setString(2, e.getLoggerName());
			stmt.setString(3, e.getLevel().toString());
			stmt.setString(4, e.getLocationInformation().getClassName() + "."
					+ e.getLocationInformation().getMethodName() + "() : "
					+ e.getLocationInformation().getLineNumber());
			stmt.setString(5, (String) e.getMessage());
			stmt.execute();
		} catch (SQLException e) {
			if (stmt != null)
				stmt.close();
			throw e;
		}
		stmt.close();
		closeConnection(con);
	}

	protected String getLogStatement(LoggingEvent event) {
		e = event;
		return getLayout().format(event);
	}
}
/*
create table LOG4J
(
  MESSAGE      VARCHAR2(400),
  LOGGERNAME   VARCHAR2(80),
  LOGLEVEL     VARCHAR2(5),
  LOCATION     VARCHAR2(100),
  LOGTIMESTAMP TIMESTAMP(6)
)
*/
